<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view
      class="fixHeader flex-y-center"
      :style="{ paddingTop: StatusBar + 'px' }"
    >
      <view class="leftbtn" @click="goBack()">
        <image
          :src="$util.img('/image/header_left.png')"
          mode="widthFix"
          style="width: 60rpx"
        ></image>
      </view>
    </view>
    <!-- 图片轮播——带右下角数量显示 -->
    <view class="advertisement m-b-30">
      <swiper
        :interval="swiperInterval"
        :autoplay="swiperAutoplay"
        :circular="true"
        indicator-active-color="#00D075"
        indicator-color="#EDEEF0"
        :indicator-dots="true"
      >
        <swiper-item
          v-for="(item, index) in goodsSkuDetail.sku_images"
          :key="index"
          @click="previewMedia(index)"
        >
          <image
            :src="$util.img(item, { size: 'big' })"
            mode="aspectFit"
            lazy-load
          ></image>
        </swiper-item>
      </swiper>
    </view>

    <view class="goodsInfo fill-base m-b-20">
      <view class="flex-between">
        <view class="font-52 c-origin flex-y-baseline text-bold">
          <text class="font-24">¥</text>{{ goodsSkuDetail.price }}
        </view>
        <view class="font-24 c-89">月销量:{{ goodsSkuDetail.sale_num }}</view>
      </view>
      <view class="font-32 name m-b-10">{{ goodsSkuDetail.goods_name }}</view>
      <view class="flex c-origin font-24">
        配送形式：
        <!-- <text v-if="goodsSkuDetail.delivery_type == '1'">快递</text>
			<text v-else-if="goodsSkuDetail.delivery_type == '0'">自提</text>
			<text v-else>自提、快递</text> -->
        <text>快递</text>
      </view>
    </view>

    <view class="fill-base goodsInfo m-b-20">
      <view class="font-32 text-bold">购买须知</view>
      <view class="c-78">
        {{ goodsSkuDetail.introduction }}
      </view>
    </view>

    <view class="fill-base goodsInfo">
      <view class="font-32 text-bold">商品详情</view>
      <view class="goods-details" v-if="goodsSkuDetail.goods_content">
        <rich-text
          :nodes="goodsSkuDetail.goods_content"
          @click="showImg($event)"
          :data-nodes="goodsSkuDetail.goods_content"
        ></rich-text>
      </view>
    </view>

    <!-- 增加推荐商品模块 -->
    <view class="m-t-24">
      <view class="font-32 text-bold m-b-10 text-center flex-center">
        <text class="line-l"></text>
        推荐商品
        <text class="line-r"></text>
      </view>
      <recommend-goods :goodsList="recommendGoodsList"></recommend-goods>
    </view>

    <view class="opetions fixfooter" :class="{ 'bottom-safe-area': isIphoneX }">
      <button class="items" open-type="share">
        <image
          :src="$util.img('/image/share.png')"
          mode=""
          style="width: 38rpx; height: 38rpx"
        ></image>
        <text>分享</text>
      </button>
      <view class="items" @click="editCollection()">
        <image
          :src="$util.img('/image/collection2.png')"
          mode=""
          v-if="whetherCollection == 1"
        ></image>
        <image :src="$util.img('/image/collection.png')" mode="" v-else></image>
        <text>收藏</text>
      </view>
      <view class="flex">
        <view class="add-cart" @click="addCart()">加入购物车</view>
        <view class="buy-now" @click="buyNow()">立即购买</view>
      </view>
    </view>

    <!-- 商品sku -->
    <goods-sku
      ref="goodsSku"
      :showGoodsSku="showGoodsSku"
      :goods-detail="goodsSkuDetail"
      @refresh="refreshGoodsSkuDetail"
      :max-buy="goodsSkuDetail.max_buy"
      :min-buy="goodsSkuDetail.min_buy"
      @close="closeGoodsSku"
    ></goods-sku>

    <!-- 悬浮购物车 -->
    <view class="cartBox" @click="$util.redirectTo('/otherpages/mall/cart')">
      <image :src="$util.img('/image/cart.png')" mode=""></image>
      <u-badge
        type="warning"
        max="99"
        :value="cartNum"
        bgColor="#FF5040"
        absolute
        :offset="offset"
      ></u-badge>
    </view>
  </view>
</template>

<script>
import recommendGoods from "@/components/recommendGoods/recommendGoods.vue";
import goodsSku from "@/components/goods-sku/goods-sku.vue";
import htmlParser from "@/common/js/html-parser";
export default {
  components: {
    goodsSku,
    recommendGoods,
  },
  data() {
    return {
      StatusBar: getApp().globalData.StatusBar,
      token: "",
      isIphoneX: false, //判断手机是否是iphoneX以上
      showGoodsSku: false,
      skuId: 0,

      // 商品详情
      goodsSkuDetail: {
        goods_id: 0,
      },
      whetherCollection: 0,

      // 解决每个商品SKU图片数量不同时，无法切换到第一个，导致轮播图显示不出来
      swiperInterval: 1,
      swiperAutoplay: false,
      recommendGoodsList: [],
      cartNum: 0, //购物车数量
      offset: [4, 0],
    };
  },
  onLoad(data) {
    this.skuId = data.sku_id || 0;
    this.isIphoneX = this.$util.uniappIsIPhoneX();
    this.getRecommendGoods();
  },
  onShow() {
    this.token = uni.getStorageSync("token");
    if (uni.getStorageSync("token")) {
      this.getCartNum();
    }

    this.getGoodsSkuDetail();
  },
  methods: {
    goBack() {
      // 判断路由是否有上一页，如果有则返回上一页，否则返回到首页
      if (getCurrentPages().length > 1) {
        uni.navigateBack();
      } else {
        this.$util.redirectTo("/pages/index/index");
      }
    },
    previewMedia(index) {
      var paths = [];
      for (let i = 0; i < this.goodsSkuDetail.sku_images.length; i++) {
        paths.push(
          this.$util.img(this.goodsSkuDetail.sku_images[i], {
            size: "big",
          })
        );
      }
      uni.previewImage({
        current: index,
        urls: paths,
      });
    },
    getCartNum() {
      this.$api.sendRequest({
        url: "/api/cart/count",
        data: {},
        success: (res) => {
          if (res.code == 0) {
            this.cartNum = res.data;
          }
        },
      });
    },
    closeGoodsSku() {
      this.showGoodsSku = false;
    },
    addCart() {
      if (this.token == "") {
        this.$util.showToast("请先登录", "none");
        return;
      }
      this.showGoodsSku = true;
    },
    buyNow() {
      // 删除待付款物流方式缓存
      uni.removeStorageSync("delivery");

      // if (!this.goodsSkuDetail.stock || this.goodsSkuDetail.stock == 0) {
      //   this.$util.showToast({
      //     title: "库存不足，暂无法购买！",
      //   });
      //   return;
      // }

      if (!uni.getStorageSync("token")) {
        this.$util.showToast({
          title: "请先登录",
        });
        return;
      }

      // 先判断是单规格还是多规格商品，如果是单规格直接跳转到提交订单页面，否则弹出选择规格弹窗
      if (
        this.goodsSkuDetail.goods_spec_format !== null &&
        this.goodsSkuDetail.goods_spec_format !== ""
      ) {
        this.showGoodsSku = true;
        return;
      }

      var data = {
        sku_id: this.skuId,
        num: 1,
      };

      uni.setStorage({
        key: "orderCreateData",
        data: data,
        success: () => {
          this.$util.redirectTo("/otherpages/mall/submitOrder");
        },
      });
    },
    goBuy() {
      this.$util.redirectTo("/otherpages/mall/submitOrder");
    },
    getRecommendGoods() {
      this.$api.sendRequest({
        url: "/api/goodssku/page",
        data: {
          page: 1,
          limit: 30,
          is_recommend_detail: 1,
        },
        success: (res) => {
          let data = res.data;
          if (data.list) this.recommendGoodsList = data.list;
        },
      });
    },
    getGoodsSkuDetail() {
      this.$api.sendRequest({
        url: "/api/goodssku/detail",
        data: {
          sku_id: this.skuId,
        },
        success: (res) => {
          let data = res.data;
          if (data.goods_sku_detail != null) {
            this.goodsSkuDetail = data.goods_sku_detail;

            if (this.skuId == 0) this.skuId = this.goodsSkuDetail.sku_id;

            //媒体
            if (this.goodsSkuDetail.video_url) this.switchMedia = "video";

            if (this.goodsSkuDetail.sku_images)
              this.goodsSkuDetail.sku_images =
                this.goodsSkuDetail.sku_images.split(",");
            else this.goodsSkuDetail.sku_images = [];

            // 多规格时合并主图
            if (
              this.goodsSkuDetail.goods_spec_format &&
              this.goodsSkuDetail.goods_image
            ) {
              this.goodsSkuDetail.goods_image =
                this.goodsSkuDetail.goods_image.split(",");
              this.goodsSkuDetail.sku_images =
                this.goodsSkuDetail.sku_images.concat(
                  this.goodsSkuDetail.goods_image
                );
            }

            this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";

            // 当前商品SKU规格
            if (this.goodsSkuDetail.sku_spec_format)
              this.goodsSkuDetail.sku_spec_format = JSON.parse(
                this.goodsSkuDetail.sku_spec_format
              );

            // 商品属性
            if (this.goodsSkuDetail.goods_attr_format) {
              let goods_attr_format = JSON.parse(
                this.goodsSkuDetail.goods_attr_format
              );
              this.goodsSkuDetail.goods_attr_format = this.$util.unique(
                goods_attr_format,
                "attr_id"
              );
              for (
                var i = 0;
                i < this.goodsSkuDetail.goods_attr_format.length;
                i++
              ) {
                for (var j = 0; j < goods_attr_format.length; j++) {
                  if (
                    this.goodsSkuDetail.goods_attr_format[i].attr_id ==
                      goods_attr_format[j].attr_id &&
                    this.goodsSkuDetail.goods_attr_format[i].attr_value_id !=
                      goods_attr_format[j].attr_value_id
                  ) {
                    this.goodsSkuDetail.goods_attr_format[i].attr_value_name +=
                      "、" + goods_attr_format[j].attr_value_name;
                  }
                }
              }
            }

            // 商品SKU格式
            if (this.goodsSkuDetail.goods_spec_format)
              this.goodsSkuDetail.goods_spec_format = JSON.parse(
                this.goodsSkuDetail.goods_spec_format
              );

            uni.setNavigationBarTitle({
              title: this.goodsSkuDetail.goods_name,
            });

            // 商品详情
            if (this.goodsSkuDetail.goods_content)
              this.goodsSkuDetail.goods_content = htmlParser(
                this.goodsSkuDetail.goods_content
              );

            if (this.token != "") {
              this.getWhetherCollection();
            }
          } else {
            this.$util.redirectTo("/pages/index/index", {}, "reLaunch");
          }
        },
      });
    },
    //获取用户是否关注
    getWhetherCollection() {
      this.$api.sendRequest({
        url: "/api/goodscollect/iscollect",
        data: {
          goods_id: this.goodsSkuDetail.goods_id,
        },
        success: (res) => {
          this.whetherCollection = res.data;
        },
      });
    },
    editCollection() {
      if (this.token) {
        //未关注添加关注
        if (this.whetherCollection == 0) {
          this.$api.sendRequest({
            url: "/api/goodscollect/add",
            data: {
              sku_id: this.skuId,
              goods_id: this.goodsSkuDetail.goods_id,
              sku_name: this.goodsSkuDetail.sku_name,
              sku_price: this.goodsSkuDetail.show_price,
              sku_image: this.goodsSkuDetail.sku_image,
            },
            success: (res) => {
              var data = res.data;
              if (data > 0) {
                this.whetherCollection = 1;
              }
            },
          });
        } else {
          //已关注取消关注
          this.$api.sendRequest({
            url: "/api/goodscollect/delete",
            data: {
              goods_id: this.goodsSkuDetail.goods_id,
            },
            success: (res) => {
              var data = res.data;
              if (data > 0) {
                this.whetherCollection = 0;
              }
            },
          });
        }
      } else {
        this.$util.showToast({title: '"请先登录"'});
      }
    },
    /**
     * 刷新商品详情数据
     * @param {Object} goodsSkuDetail
     */
    refreshGoodsSkuDetail(goodsSkuDetail) {
      Object.assign(this.goodsSkuDetail, goodsSkuDetail);
      this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";

      // 解决轮播图数量不一致时，切换到第一个
      if (this.swiperCurrent > this.goodsSkuDetail.sku_images.length) {
        this.swiperAutoplay = true;
        setTimeout(() => {
          this.swiperAutoplay = false;
        }, 40);
      }
    },
    showImg(e) {
      //拿到图片的路径里面的内容放在我们数组中
      let contentimg = e.target.dataset.nodes;
      let arrImg = [];
      for (var i = 0; i < contentimg.length; i++) {
        var img = contentimg[i].children;
        if (Array.isArray(img)) {
          for (var j = 0; j < img.length; j++) {
            if (img[j].attrs && img[j].name == "img") {
              if (img[j].attrs.src) {
                arrImg.push(img[j].attrs.src);
              }
            }
          }
        }
      }
      //最后一步就是把我们的所有图片放在预览的api中就可以了
      uni.previewImage({
        current: arrImg,
        urls: arrImg,
      });
    },
  },
  /**
   * 自定义分享内容
   * @param {Object} res
   */
  onShareAppMessage(res) {
    var path = "/otherpages/mall/detail?sku_id=" + this.skuId;
    return {
      title: this.goodsSkuDetail.sku_name,
      imageUrl: this.$util.img(this.goodsSkuDetail.sku_image, {
        size: "big",
      }),
      path: path,
      success: (res) => {},
      fail: (res) => {},
    };
  },
  // #ifdef MP-WEIXIN
  // 分享到微信朋友圈
  onShareTimeline() {
    let query = "sku_id=" + this.skuId;
    return {
      title: this.goodsSkuDetail.sku_name,
      query: query,
      imageUrl: this.$util.img(this.goodsSkuDetail.sku_image, {
        size: "big",
      }),
    };
  },
  // #endif
};
</script>

<style lang="scss" scoped>
.container {
  padding-bottom: 160rpx;
}
.fixHeader {
  position: fixed;
  top: 0;
  z-index: 9;
  width: 100%;
  box-sizing: border-box;
  .leftbtn {
    padding-left: 30rpx;
    // padding-top: 10rpx;
    margin-right: 30rpx;
    width: 60rpx;
    height: 60rpx;
  }
}
// 轮播图
.advertisement {
  position: relative;
  width: 750rpx;
  height: 750rpx;
  /deep/ swiper {
    height: 750rpx;
  }
  image {
    margin: 0 auto;
    width: 750rpx;
    height: 750rpx;
  }
}
.goodsInfo {
  padding: 30rpx 24rpx 20rpx;
  .name {
    line-height: 1.4;
  }
}

.opetions {
  padding: 10rpx 24rpx 10rpx 60rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  .items {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-right: 30rpx;
    image {
      width: 44rpx;
      height: 44rpx;
    }
    text {
      font-size: 24rpx;
      color: #606882;
    }
  }
  .add-cart {
    width: 192rpx;
    height: 86rpx;
    line-height: 86rpx;
    text-align: center;
    border-radius: 40rpx 0 0 40rpx;
    background: #ff9500;
    color: #fff;
    font-size: 26rpx;
  }
  .buy-now {
    width: 222rpx;
    height: 86rpx;
    line-height: 86rpx;
    text-align: center;
    border-radius: 0 40rpx 40rpx 0;
    background: #fe7004;
    color: #fff;
    font-size: 26rpx;
  }
}

button {
  margin: 0;
  padding: 0;
  line-height: 1.8;
}

.line-l {
  display: inline-block;
  width: 79rpx;
  height: 2rpx;
  background: linear-gradient(90deg, #cccccc00 0%, #cccccc 100%);
  margin-right: 14rpx;
}
.line-r {
  display: inline-block;
  width: 79rpx;
  height: 2rpx;
  background: linear-gradient(90deg, #cccccc 0%, #cccccc00 100%);
  margin-left: 14rpx;
}

.cartBox {
  position: fixed;
  bottom: 20%;
  right: 24rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 108rpx;
  height: 108rpx;
  border-radius: 78rpx;
  background: #fff;
  z-index: 9;
  image {
    width: 88rpx;
    height: 88rpx;
  }
}
</style>
